package com.irdstudio.apicenter.console.controller.appframe;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.irdstudio.apicenter.console.service.appframe.AppFrameStartService;
import com.irdstudio.apicenter.console.util.MacmsPathUtil;

/**
 * 文件上传的Controller
 * 
 * @author ssg
 */
@Controller
@RequestMapping("uploadpic")
public class PicFileUploadController {
	@Autowired
	private AppFrameStartService appFrameStartService;

	// private static final String FILE_PATH = "C:/uploaddir";

	@RequestMapping(value = "one", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException, SQLException,
			ClassNotFoundException {
		int i = 0;
		String sql = "";
		int flag = -1;
		String appid = request.getParameter("appid");
		String FILE_PATH = MacmsPathUtil.getMacmsAppResPath(appid);
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Iterator<String> fileNames = multipartRequest.getFileNames();
		while (fileNames.hasNext()) {
			i++;
			MultipartFile multipartFile = multipartRequest.getFile(fileNames
					.next());
			// 如果使用firebug，或者chrome的开发者工具，可以看到，这个文件上传工具发送了两个文件名
			// 分别是：name="Filedata"; filename="AVScanner.ini"
			// 用这两个文件名获得文件内容都可以，只不过第一个没有后缀，需要自己处理
			// 第二个是原始的文件名，但是这个文件名有可能是上传文件时的全路径
			// 例如 C:/testssh/a.log，如果是全路径的话，也需要处理
			String fileAlias = multipartFile.getName();
			System.out.println("Spring MVC获得的文件名：" + fileAlias);
			// 获得文件原始名称
			String name = multipartFile.getOriginalFilename();// 图片名
			String filePath = FILE_PATH + "/" + name;
			saveFile(filePath, multipartFile.getBytes());

			// 获取图片的大小尺寸
			File picture = new File(filePath);
			BufferedImage sourceImg = ImageIO
					.read(new FileInputStream(picture));
			int width = sourceImg.getWidth();
			int height = sourceImg.getHeight();
			String px = width + "*" + height + "px";// 文件的尺寸
			// 获取文件大小
			// int filesize=(new FileInputStream(picture)).available();
			if (i == 1) {
				sql = "update  app_frame_start  t   set  t.app_icon='" + name
						+ "',t.app_icon_size='" + px + "'   where app_id='"
						+ appid + "'";
				flag = appFrameStartService.updatePicInfo(sql);
			} else if (i == 2) {
				sql = "update  app_frame_start  t   set  t.APP_STARTING_ICON='"
						+ name + "',t.APP_STARTING_ICON_SIZE='" + px
						+ "'   where app_id='" + appid + "'";
				flag = appFrameStartService.updatePicInfo(sql);
			}

			Map<String, String> resultMap = new HashMap<String, String>(5);
			resultMap.put("result", "success");
			resultMap.put("filePath", filePath);
			list.add(resultMap);
		}
		return "success！";
		/*
		 * ModelAndView modelAndView = new ModelAndView();
		 * modelAndView.setViewName
		 * ("redirect:/appFrameStart/appFrameStartDetail1"); return
		 * modelAndView;
		 */

	}

	// 保存文件的方法
	public void saveFile(String filePath, byte[] content) throws IOException {
		BufferedOutputStream bos = null;
		try {
			File file = new File(filePath);
			// 判断文件路径是否存在
			if (!file.getParentFile().exists()) {
				// 文件路径不存在时，创建保存文件所需要的路径
				file.getParentFile().mkdirs();
			}
			// 创建文件（这是个空文件，用来写入上传过来的文件的内容）
			file.createNewFile();
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bos.write(content);
		} catch (FileNotFoundException e) {
			throw new FileNotFoundException("文件不存在。");
		} finally {
			if (null != bos) {
				bos.close();
			}
		}
	}

}
